import datetime
from dotenv import load_dotenv
from fastapi import FastAPI, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import HTTPBearer
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
import time

from api import api_router
from flow import create_flow
from log_config import logger
from utils.jwt_utils import ALGORITHM, SECRET_KEY, verify_token

# Import conversation service components
from services.conversation_service_v2 import process_message_stream
from model.http_models import ChatRequest

load_dotenv()
app = FastAPI(title="GGB Generation API", version="1.0.0")

security = HTTPBearer()

# 豁免路径列表
EXEMPT_PATHS = [
    "/login",
    "/api/login",
    "/api/register",
    "/docs",
    "/openapi.json",
    "/chat",  # Add chat endpoint to exempt paths
    "/api/v2/chat"  # Add v2 chat endpoint to exempt paths
]

async def verify_token_before(request: Request, call_next):
    path = request.url.path
    
    # 检查是否在豁免列表中
    if any(path.startswith(exempt) for exempt in EXEMPT_PATHS):
        return await call_next(request)
    # print(f"============= verify token path: {path} ==============")
    # 验证token
    try:
        # print("============= verify token ==============")
        credentials = await security(request)
        token = credentials.credentials
        
        payload = verify_token(token, "access")
            
        if payload is None:
            raise Exception("无效的token")
        # request.state.user = payload
        
    except Exception as e:
        logger.error(f"Token验证失败: {str(e)}")
        return JSONResponse(
            status_code=status.HTTP_401_UNAUTHORIZED,
            content={"detail": "Invalid or expired token"}
        )
    
    return await call_next(request)

app.middleware("http")(verify_token_before)

# 初始化数据库
from db_init import init_db
init_db()

# 允许跨域请求
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")

# Include existing API routes
app.include_router(api_router)

# Add conversation service routes
@app.post("/api/v2/chat")
async def chat_v2(request: ChatRequest):
    """
    Unified chat endpoint that handles both new conversations and existing ones.
    If conversation_id is provided, it will be used; otherwise, a new conversation will be created.
    """
    try:
        conversation_id = request.conversation_id
        
        # If no conversation_id is provided, create a new conversation
        if not conversation_id:
            # TODO: Implement database operations to create new conversation
            conversation_id = 1  # Placeholder, replace with actual ID from database
        
        # Return streaming response
        return StreamingResponse(
            process_message_stream(
                conversation_id=conversation_id,
                user_message=request.message,
                message_order=request.message_order or 1
            ),
            media_type="text/event-stream"
        )
    except Exception as e:
        logger.error(f"Error in chat endpoint: {str(e)}")
        return JSONResponse(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            content={"detail": str(e)}
        )

# Legacy chat endpoint for backward compatibility
@app.post("/chat")
async def chat_legacy(request: ChatRequest):
    """Legacy chat endpoint for backward compatibility"""
    return await chat_v2(request)

@app.get("/")
async def read_root(request: Request):
    return FileResponse("ui/index.html")

@app.get("/login")
async def read_root(request: Request):
    return FileResponse("ui/login.html")

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {"status": "healthy", "timestamp": datetime.datetime.now().isoformat()}

if __name__ == "__main__":
    import uvicorn
    
    uvicorn.run(app, host="0.0.0.0", port=8080)